#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016-2018, Niklas Hauser
# Copyright (c) 2017, Fabian Greif
# Copyright (c) 2018, Carl Treudler
#
# This file is part of the modm project.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# -----------------------------------------------------------------------------

def init(module):
    module.name = ":platform:adc"
    module.description = "Analog-to-Digital Converter (ADC)"

def prepare(module, options):
    device = options[":target"]
    if not (device.has_driver("adc:stm32-c0") or
            device.has_driver("adc:stm32-f0") or
            device.has_driver("adc:stm32-g0")):
        return False
    module.depends(
        ":architecture:delay",
        ":architecture:adc",
        ":architecture:register",
        ":cmsis:device",
        ":platform:gpio",
        ":platform:rcc",
        ":math:algorithm")
    return True

def build(env):
    device = env[":target"]
    driver = device.get_driver("adc")

    properties = {}
    properties["target"] = target = device.identifier
    properties["id"] = driver.get("instance", [""])[0]

    channels = {i:"In{}".format(i) for i in reversed(range(0,19))}
    if target.family in ["c0"]:
        channels[9] = "Temperature"
        channels[10] = "InternalReference"
    elif target.family in ["g0"]:
        channels[12] = "Temperature"
        channels[13] = "InternalReference"
        channels[14] = "Battery"
    else:
        channels[16] = "Temperature"
        channels[17] = "InternalReference"
        if target.name.endswith("0"):
            del channels[18]
        else:
            channels[18] = "Battery"
    properties["channels"] = channels

    irq = next(v["name"] for v in device.get_driver("core")["vector"]
               if v["name"].startswith("ADC1"))
    properties["irq"] = irq

    env.substitutions = properties
    env.outbasepath = "modm/src/modm/platform/adc"

    env.template("adc.hpp.in")
    env.template("adc_impl.hpp.in")
    env.template("adc_interrupt.hpp.in", "adc_interrupt.hpp")
    env.template("adc_interrupt.cpp.in", "adc_interrupt.cpp")
